/*
 * Author: vyouzhi <vyouzhi@163.com>
 * http://www.xda.cn
 *
 * File: memcache_lib.c
 * Create Date: 2011-07-11 15:42:31
 *
 */

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#include "client_lib.h"
#include "conf_lib.h"


int init_memcache(void){
	int mport;
	char *mhost;

	/*conf_init();	*/
	mport = atoi(conf_get("memcache_port"));
	mhost = conf_get("memcache_host");
	
	if (-1 == client_init(mhost, mport)) return (-1);
	return (0);
}

char *get_memcache(char *key){

	char *getBufs=NULL, *res, *val;
	char keybuf[1024];
	int len=0, i ;
	if( -1 == init_memcache()) return NULL;

	sprintf(keybuf, "get %s\r\n", key);

	printf("keybuf is %s\n", keybuf);

	if(-1 == client_send(keybuf, strlen(keybuf))) return NULL;

	printf("getBufs is %s\n", getBufs);

	if(-1 == client_recv(&getBufs)) return NULL;
	
	client_send("quit\r\n", strlen("quit\r\n"));

	if(getBufs == NULL) return NULL;

	getBufs = strstr(getBufs, "<?xml");

	if(getBufs == NULL) return NULL;
	
	len = strlen(getBufs);
	res = getBufs;
	i = 1;
	while(*(res+len-i) != '>'){
		i++;		
	}
	if(i < 3) return NULL;
	len = len - i + 1;
	val = (char *)calloc(len, sizeof(char));
	bzero(val, len);
	memcpy(val, getBufs, len);
	client_send("quit\r\n", strlen("quit\r\n"));
	client_close();

	return val;
}


int set_memcache(const char *val, const char *key, int extime, int val_len){
	const char *senddata , *dokey;
	int dotime, len;
	char setBufs[1024];

	senddata = val;
	dokey = key;
	dotime = extime;
	len = val_len;

	if( -1 == init_memcache()) return (-1);

	sprintf(setBufs, "set %s 0 %d %d\r\n", dokey, dotime, len);
	
	if (-1 == client_send(setBufs, strlen(setBufs))) return (-1);
	if (-1 == client_send(senddata, len)) return (-1);
	if (-1 == client_send("\r\n", 2)) return (-1);

	client_send("quit\r\n", strlen("quit\r\n"));
	client_close();

	return (0);
}

int del_memcache(const char *key){
	char setBufs[2046];

	if (-1 == init_memcache()) return (-1);

	sprintf(setBufs, "delete %s", key);

	if(-1 == client_send(setBufs, strlen(setBufs))) return (-1);
	if (-1 == client_send("\r\n", 2)) return (-1);

	client_send("quit\r\n", strlen("quit\r\n"));
	client_close();

	return (0);

}
/* vim: set ts=4 sw=4: */

